import 'dart:async';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:rxdart/rxdart.dart';
import 'package:just_audio/just_audio.dart';
import 'package:path/path.dart' as p;
import '../models/music_model.dart';

// 播放模式枚举
enum PlayMode {
  sequence,
  shuffle,
  repeatOne
}

class AudioService with ChangeNotifier{

  // 添加单例实例和工厂构造函数
  static final AudioService _instance = AudioService._internal();
  factory AudioService() {
    return _instance;
  }

  final AudioPlayer _audioPlayer = AudioPlayer();

  final BehaviorSubject<PlayerState> _playerStateSubject = BehaviorSubject.seeded(PlayerState(false ,ProcessingState.idle));
  final BehaviorSubject<Duration> _positionSubject = BehaviorSubject.seeded(Duration.zero);
  final BehaviorSubject<Duration?> _durationSubject = BehaviorSubject.seeded(null);
  final BehaviorSubject<Music?> _currentMusicSubject = BehaviorSubject.seeded(null);
  final BehaviorSubject<PlayMode> _playModeSubject = BehaviorSubject.seeded(PlayMode.sequence);  // 添加播放模式流
  final BehaviorSubject<double> _volumeSubject = BehaviorSubject.seeded(1.0);

  // 播放列表和当前索引
  List<Music> _playlist = [];
  int _currentIndex = -1;
  // 添加当前播放模式
  PlayMode _currentMode = PlayMode.sequence;
  // 随机播放历史，用于避免重复
  List<int> _shuffleHistory = [];

  Stream<Duration> get positionStream => _positionSubject.stream;
  Stream<Duration?> get durationStream => _durationSubject.stream;
  // 暴露音量流
  Stream<double> get volumeStream => _volumeSubject.stream;
  //暴漏当前播放状态
  PlayerState get currentState => _playerStateSubject.value;
  Music? get currentMusic => _currentMusicSubject.value;
  PlayMode? get currentPlayMode => _playModeSubject.value;

  // 登录 Cookie
  String _cookie = '';
  String get cookie => _cookie;
  void setCookie(val) {
    _cookie = val;
    notifyListeners();
  }

  bool _isLogin = false;
  bool get isLogin => _isLogin;
  void setLogin(val) {
    _isLogin = val;
    notifyListeners();
  }

  AudioService._internal() {
    print('playStore已经被创建');
    // 监听播放状态变化
    _audioPlayer.playerStateStream.listen((state) {
      _playerStateSubject.add(state);
      if (state.processingState == ProcessingState.ready) {
        _audioPlayer.play(); // 加载完成后自动播放
      }
      // 播放结束时根据模式处理
      if (state.processingState == ProcessingState.completed) {
        if (_currentMode == PlayMode.repeatOne) {
          // 单曲循环 - 重新播放当前歌曲
          playIndex(_currentIndex);
        } else {
          // 其他模式 - 播放下一首
          playNext();
        }
      }
    });

    // 监听进度和时长变化
    _audioPlayer.positionStream.listen(_positionSubject.add);
    _audioPlayer.durationStream.listen(_durationSubject.add);
  }
  
  // 添加切换播放模式的方法
  void togglePlayMode() {
    switch (_currentMode) {
        case PlayMode.sequence:
          _currentMode = PlayMode.shuffle;
          break;
        case PlayMode.shuffle:
          _currentMode = PlayMode.repeatOne;
          break;
        case PlayMode.repeatOne:
          _currentMode = PlayMode.sequence;
          break;
      }
      _playModeSubject.add(_currentMode);
      // 重置随机历史
      _shuffleHistory.clear();
    notifyListeners();
  }

  // 设置播放列表
  void setPlaylist(List<Music> playlist) {
    _playlist = List.from(playlist);
    notifyListeners();
  }

  // 播放指定索引的音乐
  Future<void> playIndex(int index) async {
    if (index < 0 || index >= _playlist.length) return;

    _currentIndex = index;
    final music = _playlist[index];
    _currentMusicSubject.add(music);

    // 添加当前索引到随机历史
    if (_currentMode == PlayMode.shuffle && !_shuffleHistory.contains(index)) {
      _shuffleHistory.add(index);
      // 如果历史长度等于播放列表长度，重置历史
      if (_shuffleHistory.length == _playlist.length) {
        _shuffleHistory.clear();
        _shuffleHistory.add(index);
      }
    }

    try {
      if (music.path != null && music.path!.isNotEmpty) {
        await _audioPlayer.setFilePath(music.path!);
      } else if (music.url != null && music.url!.isNotEmpty) {
        await _audioPlayer.setUrl(music.url!);
      }

      await _audioPlayer.play();
      // 验证播放状态
      if (!_audioPlayer.playerState.playing) {
        print('播放命令已发送，但播放器未处于播放状态');
        // 尝试再次播放
        await Future.delayed(Duration(milliseconds: 100));
        await _audioPlayer.play();
      }
    } catch (e) {
      print('播放错误: \$e');
    }
    notifyListeners();
  }

  // 播放/暂停切换
  Future<void> togglePlayPause() async {
    if (_currentIndex == -1 && _playlist.isNotEmpty) {
      await playIndex(0); // 如果没有播放任何歌曲且有播放列表，播放第一首
      notifyListeners();
      return;
    }

    if (_audioPlayer.playerState.playing) {
      await pause();
    } else {
      await resume();
    }
    notifyListeners();
  }

  // 暂停
  Future<void> pause() async {
    await _audioPlayer.pause();
    notifyListeners();
  }

  // 继续播放
  Future<void> resume() async {
    await _audioPlayer.play();
    notifyListeners();
  }

  // 停止
  Future<void> stop() async {
    await _audioPlayer.stop();
    _currentMusicSubject.add(null);
    _currentIndex = -1;
    notifyListeners();
  }

  // 上一首
  Future<void> playPrevious() async {
    if (_playlist.isEmpty) return;

    int newIndex;
    switch (_currentMode) {
      case PlayMode.shuffle:
        // 随机模式下播放历史中的上一首
        if (_shuffleHistory.length > 1) {
          _shuffleHistory.removeLast();
          newIndex = _shuffleHistory.last;
        } else {
          newIndex = _getRandomIndex();
        }
        break;
      case PlayMode.repeatOne:
        // 单曲循环 - 保持当前索引
        newIndex = _currentIndex;
        break;
      default:
        // 顺序模式
        newIndex = (_currentIndex - 1 + _playlist.length) % _playlist.length;
        break;
    }

    await playIndex(newIndex);
  }

  // 下一首
  Future<void> playNext() async {
    if (_playlist.isEmpty) return;

    int newIndex;
    switch (_currentMode) {
      case PlayMode.shuffle:
        newIndex = _getRandomIndex();
        break;
      case PlayMode.repeatOne:
        // 单曲循环 - 保持当前索引
        newIndex = _currentIndex;
        break;
      default:
        // 顺序模式
        newIndex = (_currentIndex + 1) % _playlist.length;
        break;
    }

    await playIndex(newIndex);
  }

  
  // 生成随机索引（避免重复）
  int _getRandomIndex() {
    if (_playlist.length == 1) return 0;

    int newIndex;
    do {
      newIndex = Random().nextInt(_playlist.length);
    } while (
      newIndex == _currentIndex || 
      (_shuffleHistory.length < _playlist.length && _shuffleHistory.contains(newIndex))
    );
    return newIndex;
  }


  // 进度调整
  Future<void> seek(Duration position) async {
    await _audioPlayer.seek(position);
    notifyListeners();
  }

  // 音量控制
  Future<void> setVolume(double volume) async {
    await _audioPlayer.setVolume(volume);
    notifyListeners();
  }

  void dispose() {
    _audioPlayer.dispose();
    _playerStateSubject.close();
    _positionSubject.close();
    _durationSubject.close();
    _currentMusicSubject.close();
    _playModeSubject.close() ;
    _volumeSubject.close();
  }
}